package ar.republicagroup.gestion.view;

import ar.republicagroup.gestion.entities.CalendarioBancario;
import ar.republicagroup.gestion.entities.Cheque;
import ar.republicagroup.gestion.entities.CuentaBanco;
import ar.republicagroup.gestion.services.CalendarioBancarioServices;
import ar.republicagroup.gestion.services.ChequeServices;
import ar.republicagroup.gestion.services.CuentaBancoServices;
import ar.republicagroup.gestion.util.JComboBoxModel;
import ar.republicagroup.gestion.util.SpringUtils;
import ar.republicagroup.gestion.util.TableColumnAdjuster;
import ar.republicagroup.gestion.util.helpers.Formato;
import ar.republicagroup.gestion.util.messages.UIMessages;
import java.awt.Color;
import java.awt.Component;
import java.awt.HeadlessException;
import java.awt.print.PrinterException;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import org.apache.log4j.Logger;

public class frmReporteTotalesPorCuenta extends javax.swing.JFrame {
    CuentaBancoServices cuentaBancoServices     = (CuentaBancoServices)SpringUtils.getBean("cuentaBancoServices");
    CalendarioBancarioServices calendarioBancarioServices = (CalendarioBancarioServices)SpringUtils.getBean("calendarioBancarioServices");
    ChequeServices chequeServices = (ChequeServices)SpringUtils.getBean("chequeServices");
    /* Listados */
    Set<CalendarioBancario> calendarioSet = new HashSet<>();
    List<Cheque> chequeList;
    Calendar fechaSeleccionada;
    /*Totales*/
    double totalPorCuenta = 0 ;
    
    Logger log  = Logger.getLogger(frmReporteTotalesPorCuenta.class);
    
    public frmReporteTotalesPorCuenta() {
        initComponents();
        cargarDatos();
        valoresPorDefecto();
        pintarFeriadosEnCalendario();
        this.setIconImage(new ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/moneybox.png")).getImage());
    }

    private void cargarDatos(){
        comboCuentas.setModel(cuentaBancoServices.combo());
        jCalendar1.setLocale(Formato.localeDeCalendario());
        calendarioSet = calendarioBancarioServices.findEntities();
    }
    
    private void valoresPorDefecto(){
        fechaSeleccionada = Calendar.getInstance();
        mostrarFecha(fechaSeleccionada);       
    }
    
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        comboCuentas = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        btnVerDetalle = new javax.swing.JButton();
        txtFecha = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jCalendar1 = new com.toedter.calendar.JCalendar();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblReporteTotPorCuenta = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        lblNroDeCheques = new javax.swing.JLabel();
        lblMontoTotal = new javax.swing.JLabel();
        btnImprimir = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("...: Totales por cuenta :...");

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Seleccione fecha y cuenta"));

        jLabel1.setText("Cuenta:");

        btnVerDetalle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/search_binoculars.png"))); // NOI18N
        btnVerDetalle.setText("Ver detalle");
        btnVerDetalle.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        btnVerDetalle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVerDetalleActionPerformed(evt);
            }
        });

        txtFecha.setEditable(false);

        jLabel4.setText("Fecha seleccionada");

        jCalendar1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jCalendar1PropertyChange(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jCalendar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(comboCuentas, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel1)
                        .addComponent(btnVerDetalle, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
                        .addComponent(txtFecha))
                    .addComponent(jLabel4))
                .addGap(40, 40, 40))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(comboCuentas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnVerDetalle)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jCalendar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        tblReporteTotPorCuenta.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nro.Cheque", "Fecha alta", "Banco emisor", "Cuenta destino", "Importe"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblReporteTotPorCuenta.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jScrollPane1.setViewportView(tblReporteTotPorCuenta);

        jLabel2.setText("Total");

        jLabel3.setText("Cheques");

        lblNroDeCheques.setText("0");

        lblMontoTotal.setText("0");

        btnImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/printer.png"))); // NOI18N
        btnImprimir.setText("Imprimir");
        btnImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImprimirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 600, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(18, 18, 18)
                        .addComponent(lblNroDeCheques)
                        .addGap(42, 42, 42)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblMontoTotal)
                        .addGap(321, 321, 321)
                        .addComponent(btnImprimir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 268, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(lblNroDeCheques)
                    .addComponent(jLabel2)
                    .addComponent(lblMontoTotal)
                    .addComponent(btnImprimir))
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(151, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public void cargarTablaCheque(List<Cheque> listado){
        DefaultTableModel model = (DefaultTableModel) tblReporteTotPorCuenta.getModel();
        model.getDataVector().clear();
       
        for(Cheque cheque : listado){
            model.addRow(new Object[]{cheque,Formato.fechaDDMMYY(cheque.getFechaAlta()),cheque.getBancoId().getNombre(),cheque.getCuentaBancoId().getNombre(),Formato.decimalComaMilesConSigno(cheque.getImporte().doubleValue()) });
            totalPorCuenta += cheque.getImporte().doubleValue();
        }
        
        TableColumnAdjuster tca = new TableColumnAdjuster(tblReporteTotPorCuenta);
        tca.adjustColumns();
         
        tblReporteTotPorCuenta.setAutoCreateRowSorter(false);
        tblReporteTotPorCuenta.setModel(model);
        tblReporteTotPorCuenta.repaint();
    }
    
    
    
    private void jCalendar1PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jCalendar1PropertyChange
       if ("calendar".equals(evt.getPropertyName())) {
            System.out.println(evt.getPropertyName()
                + ": " + (Calendar) evt.getNewValue());
            fechaSeleccionada = (Calendar)evt.getNewValue();
            mostrarFecha(fechaSeleccionada);
            pintarFeriadosEnCalendario();
        }     
    }//GEN-LAST:event_jCalendar1PropertyChange

    private void btnVerDetalleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVerDetalleActionPerformed
        totalPorCuenta = 0;
        JComboBoxModel model = (JComboBoxModel)comboCuentas.getSelectedItem();
        CuentaBanco cuentaSeleccionada = cuentaBancoServices.get(Integer.valueOf(model.getValue()));
        chequeList = chequeServices.getChequesByFilters(null, null, cuentaSeleccionada, fechaSeleccionada,null,0);
        cargarTablaCheque(chequeList);
        lblNroDeCheques.setText(String.valueOf(chequeList.size()));
        lblMontoTotal.setText(Formato.decimalComaMilesConSigno(totalPorCuenta));        
    }//GEN-LAST:event_btnVerDetalleActionPerformed

    private void btnImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImprimirActionPerformed
        try {
            MessageFormat header = new MessageFormat(UIMessages.getInfoMessage("totalesPorCuenta_title")+" "+comboCuentas.getSelectedItem());
            boolean imprimio = tblReporteTotPorCuenta.print(JTable.PrintMode.NORMAL, header, null, true, null, true);
                if(imprimio){
                    log.info("Imprimió reporte de Liquidaciones posibles...");
                }
            } catch (PrinterException ex) {
                log.error("Error al imprimir...",ex);
                log.error(ex.getMessage());
            } catch (HeadlessException ex) {
                log.error(ex.getMessage());
                log.error("Sin encabezado ...",ex);
            }
        
        
    }//GEN-LAST:event_btnImprimirActionPerformed

    private void pintarFeriadosEnCalendario(){
        Calendar cal = Calendar.getInstance();
        cal.setTime(jCalendar1.getDate());
        int currentMonth = cal.get(Calendar.MONTH);
        int currentYear = cal.get(Calendar.YEAR);
       
        JPanel jPanel = jCalendar1.getDayChooser().getDayPanel();
        Component component[] = jPanel.getComponents();
         
        
            for(CalendarioBancario feriado : calendarioSet){
                Calendar feriadito = Calendar.getInstance(); 
                feriadito.setTime(feriado.getFechaFeriado());
                
                int mesDelFeriado = feriadito.get(Calendar.MONTH);
                int anoDelFeriado = feriadito.get(Calendar.YEAR);
                
                if((currentMonth == mesDelFeriado) && (currentYear == anoDelFeriado)){
                     // Calculate the offset of the first day of the month
                    cal.set(Calendar.DAY_OF_MONTH,1);
                    int offset = cal.get(Calendar.DAY_OF_WEEK) - 1;
                    component[ feriado.getFechaFeriado().getDate() - 1  + offset + 7 ].setBackground(Color.RED);
                    component[ feriado.getFechaFeriado().getDate() - 1  + offset + 7 ].setEnabled(false);
                }
            }
    }
    
    
    
    public void mostrarFecha(Calendar fecha){
        txtFecha.setText(Formato.fechaDDMMYY(fecha.getTime()));
    }
    
    
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmReporteTotalesPorCuenta().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnImprimir;
    private javax.swing.JButton btnVerDetalle;
    private javax.swing.JComboBox comboCuentas;
    private com.toedter.calendar.JCalendar jCalendar1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblMontoTotal;
    private javax.swing.JLabel lblNroDeCheques;
    private javax.swing.JTable tblReporteTotPorCuenta;
    private javax.swing.JTextField txtFecha;
    // End of variables declaration//GEN-END:variables
}
